{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "2bc772ec-b9b2-4848-9f61-b879274d3318",
   "metadata": {},
   "source": [
    "# CrewAI Tool calling capabilities with Unity Catalog\n",
    "\n",
    "## Prerequisites\n",
    "\n",
    "**API Key**\n",
    "To run this tutorial, you will need an OpenAI API key. \n",
    "\n",
    "Once you have acquired your key, set it to the environment variable `OPENAI_API_KEY`.\n",
    "\n",
    "Below, we validate that this key is set properly in your environment.\n",
    "\n",
    "**Packages**\n",
    "\n",
    "To interface with both UnityCatalog and CrewAI, you will need to install the following packages:\n",
    "\n",
    "```shell\n",
    "pip install crewai unitycatalog-crewai\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "ea25b105-2850-4a70-91c0-8cf68731a009",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "assert \"OPENAI_API_KEY\" in os.environ, (\n",
    "    \"Please set the OPENAI_API_KEY environment variable to your OpenAI API key\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "09406069-0990-48b2-b70b-b002beffe11e",
   "metadata": {},
   "source": [
    "## Configuration and Client setup\n",
    "\n",
    "In order to connect to your Unity Catalog server, you'll need an instance of the `ApiClient` from the `unitycatalog-client` package. \n",
    "\n",
    "> Note: If you don't already have a Catalog and a Schema created, be sure to create them before running this notebook and adjust the `CATALOG` and `SCHEMA` variables below to suit."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fa8d7a71-813d-4b34-be75-e547709786b7",
   "metadata": {},
   "outputs": [],
   "source": [
    "from unitycatalog.ai.core.client import UnitycatalogFunctionClient\n",
    "from unitycatalog.ai.crewai.toolkit import UCFunctionToolkit\n",
    "from unitycatalog.client import ApiClient, Configuration"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "75c54c74-39f0-48cf-9e90-2221b468ded0",
   "metadata": {},
   "outputs": [],
   "source": [
    "config = Configuration()\n",
    "config.host = \"http://localhost:8080/api/2.1/unity-catalog\"\n",
    "\n",
    "# The base ApiClient is async\n",
    "api_client = ApiClient(configuration=config)\n",
    "\n",
    "client = UnitycatalogFunctionClient(api_client=api_client)\n",
    "\n",
    "CATALOG = \"AICatalog\"\n",
    "SCHEMA = \"AISchema\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7cc47548-de04-4a33-990f-d5e055fde212",
   "metadata": {},
   "source": [
    "## Define functions and register them to Unity Catalog\n",
    "\n",
    "In this next section, we'll be defining two Python functions and creating them within Unity Catalog so that they can be retrieved and used as tools within our CrewAI [Crews](https://docs.crewai.com/concepts/crews). \n",
    "\n",
    "There are a few things to keep in mind when creating functions for use with the `create_python_function` API:\n",
    "\n",
    "- Ensure that your have properly defined types for all arguments and for the return of the function.\n",
    "- Ensure that you have a Google-style docstring defined that includes descriptions for the function, each argument, and the return of the function. This is critical, as these are used to populate the metadata associated with the function within Unity Catalog, providing contextual data for an LLM to understand when and how to call the tool associated with this function.\n",
    "- If there are packages being called that are not part of core Python, ensure that the import statements are locally scoped (defined within the function body)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "a3d42fcf-d516-4b69-b796-764e2a33102f",
   "metadata": {},
   "outputs": [],
   "source": [
    "def calculate_delta_v(exhaust_velocity: float, initial_mass: float, final_mass: float) -> float:\n",
    "    \"\"\"\n",
    "    Calculates the maximum change in velocity (delta-v) of a rocket using the Ideal Rocket Equation (Tsiolkovsky Equation).\n",
    "\n",
    "    The Ideal Rocket Equation is given by:\n",
    "        delta_v = exhaust_velocity * ln(initial_mass / final_mass)\n",
    "\n",
    "    This calculation is tailored for missions departing from Earth.\n",
    "\n",
    "    Args:\n",
    "        exhaust_velocity: The effective exhaust velocity of the rocket's engine in meters per second (m/s).\n",
    "        initial_mass: The initial total mass of the rocket, including propellant, in kilograms (kg).\n",
    "        final_mass: The final total mass of the rocket after propellant has been expended, in kilograms (kg).\n",
    "\n",
    "    Returns:\n",
    "        The maximum change in velocity (delta-v) achievable by the rocket in meters per second (m/s).\n",
    "    \"\"\"\n",
    "    import math  # local imports are required for functions in Unity Catalog\n",
    "\n",
    "    if exhaust_velocity <= 0:\n",
    "        raise ValueError(\"Exhaust velocity must be positive.\")\n",
    "    if initial_mass <= final_mass:\n",
    "        raise ValueError(\"Initial mass must be greater than final mass.\")\n",
    "\n",
    "    mass_ratio = initial_mass / final_mass\n",
    "    delta_v = exhaust_velocity * math.log(mass_ratio)\n",
    "    return delta_v\n",
    "\n",
    "\n",
    "def earth_escape_velocity() -> float:\n",
    "    \"\"\"\n",
    "    Calculates the escape velocity required to break free from Earth's gravitational pull.\n",
    "\n",
    "    The escape velocity from Earth is calculated using the formula:\n",
    "        escape_velocity = sqrt(2 * G * M / R)\n",
    "\n",
    "    where:\n",
    "        G is the universal gravitational constant,\n",
    "        M is the mass of Earth,\n",
    "        R is the radius of Earth.\n",
    "\n",
    "    Constants:\n",
    "        - Gravitational Constant (G): 6.67430e-11 m^3 kg^-1 s^-2\n",
    "        - Mass of Earth (M): 5.972e24 kg\n",
    "        - Radius of Earth (R): 6.371e6 meters\n",
    "\n",
    "    Returns:\n",
    "        The escape velocity from Earth in meters per second (m/s).\n",
    "    \"\"\"\n",
    "    import math\n",
    "\n",
    "    GRAVITATIONAL_CONSTANT = 6.67430e-11  # m^3 kg^-1 s^-2\n",
    "    EARTH_MASS = 5.972e24  # kg\n",
    "    EARTH_RADIUS = 6.371e6  # meters\n",
    "\n",
    "    escape_vel = math.sqrt(2 * GRAVITATIONAL_CONSTANT * EARTH_MASS / EARTH_RADIUS)\n",
    "    return escape_vel"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "c71075a3-9788-493b-b279-bff7576da017",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "FunctionInfo(name='calculate_delta_v', catalog_name='AICatalog', schema_name='AISchema', input_params=FunctionParameterInfos(parameters=[FunctionParameterInfo(name='exhaust_velocity', type_text='DOUBLE', type_json='{\"name\": \"exhaust_velocity\", \"type\": \"double\", \"nullable\": false, \"metadata\": {\"comment\": \"The effective exhaust velocity of the rocket\\\\\"s engine in meters per second (m/s).\"}}', type_name=<ColumnTypeName.DOUBLE: 'DOUBLE'>, type_precision=None, type_scale=None, type_interval_type=None, position=0, parameter_mode=None, parameter_type=None, parameter_default=None, comment='The effective exhaust velocity of the rocket\"s engine in meters per second (m/s).'), FunctionParameterInfo(name='initial_mass', type_text='DOUBLE', type_json='{\"name\": \"initial_mass\", \"type\": \"double\", \"nullable\": false, \"metadata\": {\"comment\": \"The initial total mass of the rocket, including propellant, in kilograms (kg).\"}}', type_name=<ColumnTypeName.DOUBLE: 'DOUBLE'>, type_precision=None, type_scale=None, type_interval_type=None, position=1, parameter_mode=None, parameter_type=None, parameter_default=None, comment='The initial total mass of the rocket, including propellant, in kilograms (kg).'), FunctionParameterInfo(name='final_mass', type_text='DOUBLE', type_json='{\"name\": \"final_mass\", \"type\": \"double\", \"nullable\": false, \"metadata\": {\"comment\": \"The final total mass of the rocket after propellant has been expended, in kilograms (kg).\"}}', type_name=<ColumnTypeName.DOUBLE: 'DOUBLE'>, type_precision=None, type_scale=None, type_interval_type=None, position=2, parameter_mode=None, parameter_type=None, parameter_default=None, comment='The final total mass of the rocket after propellant has been expended, in kilograms (kg).')]), data_type=<ColumnTypeName.DOUBLE: 'DOUBLE'>, full_data_type='DOUBLE', return_params=None, routine_body='EXTERNAL', routine_definition='import math  # local imports are required for functions in Unity Catalog\\n\\nif exhaust_velocity <= 0:\\n    raise ValueError(\"Exhaust velocity must be positive.\")\\nif initial_mass <= final_mass:\\n    raise ValueError(\"Initial mass must be greater than final mass.\")\\n\\nmass_ratio = initial_mass / final_mass\\ndelta_v = exhaust_velocity * math.log(mass_ratio)\\nreturn delta_v', routine_dependencies=None, parameter_style='S', is_deterministic=True, sql_data_access='NO_SQL', is_null_call=False, security_type='DEFINER', specific_name='calculate_delta_v', comment='Calculates the maximum change in velocity (delta-v) of a rocket using the Ideal Rocket Equation (Tsiolkovsky Equation). The Ideal Rocket Equation is given by: delta_v = exhaust_velocity * ln(initial_mass / final_mass) This calculation is tailored for missions departing from Earth.', properties='null', full_name='AICatalog.AISchema.calculate_delta_v', owner=None, created_at=1732654439024, created_by=None, updated_at=1732654439024, updated_by=None, function_id='ef434abe-b2cf-495c-b814-c781af6b2ca1', external_language='PYTHON')"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "client.create_python_function(func=calculate_delta_v, catalog=CATALOG, schema=SCHEMA, replace=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "5c5b63b6-867d-493e-a429-e930c2d3edc2",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "FunctionInfo(name='earth_escape_velocity', catalog_name='AICatalog', schema_name='AISchema', input_params=FunctionParameterInfos(parameters=[]), data_type=<ColumnTypeName.DOUBLE: 'DOUBLE'>, full_data_type='DOUBLE', return_params=None, routine_body='EXTERNAL', routine_definition='import math\\n\\nGRAVITATIONAL_CONSTANT = 6.67430e-11  # m^3 kg^-1 s^-2\\nEARTH_MASS = 5.972e24  # kg\\nEARTH_RADIUS = 6.371e6  # meters\\n\\nescape_vel = math.sqrt(2 * GRAVITATIONAL_CONSTANT * EARTH_MASS / EARTH_RADIUS)\\nreturn escape_vel', routine_dependencies=None, parameter_style='S', is_deterministic=True, sql_data_access='NO_SQL', is_null_call=False, security_type='DEFINER', specific_name='earth_escape_velocity', comment=\"Calculates the escape velocity required to break free from Earth's gravitational pull. The escape velocity from Earth is calculated using the formula: escape_velocity = sqrt(2 * G * M / R) where: G is the universal gravitational constant, M is the mass of Earth, R is the radius of Earth. Constants: - Gravitational Constant (G): 6.67430e-11 m^3 kg^-1 s^-2 - Mass of Earth (M): 5.972e24 kg - Radius of Earth (R): 6.371e6 meters\", properties='null', full_name='AICatalog.AISchema.earth_escape_velocity', owner=None, created_at=1732654439921, created_by=None, updated_at=1732654439921, updated_by=None, function_id='0476caf7-d484-4578-b844-21516e41808d', external_language='PYTHON')"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "client.create_python_function(\n",
    "    func=earth_escape_velocity, catalog=CATALOG, schema=SCHEMA, replace=True\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d2fb055e-45fb-4931-a7bd-42fe4d5c6eba",
   "metadata": {},
   "source": [
    "## Create a Toolkit instance of the functions\n",
    "\n",
    "Now that the functions have been created within Unity Catalog, we can use the `unitycatalog-crewai` package to create a toolkit instance that our Agent will 'understand' as valid tools to use within its APIs. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "837ab7d9-3b91-4e53-b317-2c41afb7d070",
   "metadata": {},
   "outputs": [],
   "source": [
    "escape_vel_func = f\"{CATALOG}.{SCHEMA}.earth_escape_velocity\"\n",
    "delta_v_func = f\"{CATALOG}.{SCHEMA}.calculate_delta_v\"\n",
    "\n",
    "toolkit = UCFunctionToolkit(function_names=[escape_vel_func, delta_v_func], client=client)\n",
    "\n",
    "tools = toolkit.tools"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "b3a9ea75-9ae2-4a6e-95c7-30320b58da94",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[UnityCatalogTool(name='AICatalog__AISchema__earth_escape_velocity', description=\"Tool Name: AICatalog__AISchema__earth_escape_velocity\\nTool Arguments: {}\\nTool Description: Calculates the escape velocity required to break free from Earth's gravitational pull. The escape velocity from Earth is calculated using the formula: escape_velocity = sqrt(2 * G * M / R) where: G is the universal gravitational constant, M is the mass of Earth, R is the radius of Earth. Constants: - Gravitational Constant (G): 6.67430e-11 m^3 kg^-1 s^-2 - Mass of Earth (M): 5.972e24 kg - Radius of Earth (R): 6.371e6 meters\", args_schema=<class 'unitycatalog.ai.core.utils.function_processing_utils.AICatalog__AISchema__earth_escape_velocity__params'>, description_updated=False, cache_function=<function UCFunctionToolkit.<lambda> at 0x306f67b00>, result_as_answer=False, fn=<function UCFunctionToolkit.uc_function_to_crewai_tool.<locals>.func at 0x10886dc60>, client_config={'uc': <unitycatalog.client.api.functions_api.FunctionsApi object at 0x30720cd10>}),\n",
       " UnityCatalogTool(name='AICatalog__AISchema__calculate_delta_v', description='Tool Name: AICatalog__AISchema__calculate_delta_v\\nTool Arguments: {\\'exhaust_velocity\\': {\\'description\\': \\'The effective exhaust velocity of the rocket\"s engine in meters per second (m/s).\\', \\'type\\': \\'float\\'}, \\'initial_mass\\': {\\'description\\': \\'The initial total mass of the rocket, including propellant, in kilograms (kg).\\', \\'type\\': \\'float\\'}, \\'final_mass\\': {\\'description\\': \\'The final total mass of the rocket after propellant has been expended, in kilograms (kg).\\', \\'type\\': \\'float\\'}}\\nTool Description: Calculates the maximum change in velocity (delta-v) of a rocket using the Ideal Rocket Equation (Tsiolkovsky Equation). The Ideal Rocket Equation is given by: delta_v = exhaust_velocity * ln(initial_mass / final_mass) This calculation is tailored for missions departing from Earth.', args_schema=<class 'unitycatalog.ai.core.utils.function_processing_utils.AICatalog__AISchema__calculate_delta_v__params'>, description_updated=False, cache_function=<function UCFunctionToolkit.<lambda> at 0x306f67b00>, result_as_answer=False, fn=<function UCFunctionToolkit.uc_function_to_crewai_tool.<locals>.func at 0x3124a8040>, client_config={'uc': <unitycatalog.client.api.functions_api.FunctionsApi object at 0x30720cd10>})]"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "tools"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ac0888dc-96e5-425b-b4ff-455290eea963",
   "metadata": {},
   "source": [
    "## Create a Crew\n",
    "\n",
    "Now that everything is all set for our tools that we want to use in our Crew, we can create it. \n",
    "We're going to define the Agents that will be in use, marking one of the tasks as requiring human input (so that we can ask a question to the Aeronautical Engineer). The tools will be added to this agent so that it can have access to our deterministic functions that reside within Unity Catalog. \n",
    "\n",
    "> **IMPORTANT DISCLAIMER**:\n",
    "This implementation constitutes an extremely rudimentary approximation intended exclusively for educational and recreational purposes within the context of this demonstration. In real-world aerospace engineering and mission planning, rocket launch simulations necessitate the utilization of advanced numerical integration methodologies such as Runge-Kutta algorithms, comprehensive atmospheric modeling, intricate multi-stage rocket dynamic differential equations, and the incorporation of orbital mechanics solutions, including but not limited to the two-body problem for precise orbital trajectory calculations.\n",
    "\n",
    "> **WARNING**:\n",
    "The algorithms and models presented herein lack the sophistication, accuracy, and reliability required for any form of practical application, including but not limited to spacecraft navigation, mission-critical operations, or aerospace engineering endeavors.\n",
    "\n",
    "> **CAUTION**:\n",
    "Attempting to utilize this example for actual rocket launches or space travel may result in catastrophic failure and is unequivocally advised against. Always consult with qualified aerospace professionals and employ industry-standard simulation tools for any endeavors related to space exploration."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "cebf9bfc-83a4-423d-83c4-fa0597ea0d36",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[1m\u001b[93m \n",
      "[2024-11-26 15:54:05][INFO]: Planning the crew execution\u001b[00m\n",
      "\u001b[1m\u001b[95m# Agent:\u001b[00m \u001b[1m\u001b[92mAeronautical Engineer\u001b[00m\n",
      "\u001b[95m## Task:\u001b[00m \u001b[92mCall tools that are relevant to the posed questionBased on the review of outputs, collate findings and direct responses to the original query while ensuring clarity and accuracy. Highlight any specific aeronautical engineering principles that are relevant to the results.\u001b[00m\n",
      "\n",
      "\n",
      "\u001b[1m\u001b[95m# Agent:\u001b[00m \u001b[1m\u001b[92mAeronautical Engineer\u001b[00m\n",
      "\u001b[95m## Thought:\u001b[00m \u001b[92mI need to determine whether I should calculate the escape velocity from Earth or find the delta-v of a rocket. It depends on the context of the question posed. If the goal is to understand the conditions required for spacecraft to leave Earth's gravitational influence, then escape velocity is relevant. If the question relates to the performance of a rocket in terms of changing its velocity to reach a specific orbit or destination, then the delta-v is more pertinent. \n",
      "Since I'm currently equipped to provide calculations for both aspects, I will calculate the escape velocity from Earth first, as it's a fundamental concept in getting into space.\u001b[00m\n",
      "\u001b[95m## Using tool:\u001b[00m \u001b[92mAICatalog__AISchema__earth_escape_velocity\u001b[00m\n",
      "\u001b[95m## Tool Input:\u001b[00m \u001b[92m\n",
      "\"{}\"\u001b[00m\n",
      "\u001b[95m## Tool Output:\u001b[00m \u001b[92m\n",
      "{\"format\": \"SCALAR\", \"value\": \"11185.97789184991\"}\u001b[00m\n",
      "\n",
      "\n",
      "\u001b[1m\u001b[95m# Agent:\u001b[00m \u001b[1m\u001b[92mAeronautical Engineer\u001b[00m\n",
      "\u001b[95m## Final Answer:\u001b[00m \u001b[92m\n",
      "The escape velocity required to break free from Earth's gravitational pull is approximately 11,186 meters per second (m/s). This velocity is crucial for spacecraft to reach outer space without being pulled back by Earth's gravity. In aeronautical engineering, understanding escape velocity informs the design of propulsion systems, the amount of fuel required, and the overall mass of the rocket. Achieving this velocity is fundamental in mission planning and launch vehicle design to ensure that spacecraft can successfully enter orbit or travel to other celestial bodies.\u001b[00m\n",
      "\n",
      "\n",
      "\u001b[1m\u001b[95m ## Final Result:\u001b[00m \u001b[92mThe escape velocity required to break free from Earth's gravitational pull is approximately 11,186 meters per second (m/s). This velocity is crucial for spacecraft to reach outer space without being pulled back by Earth's gravity. In aeronautical engineering, understanding escape velocity informs the design of propulsion systems, the amount of fuel required, and the overall mass of the rocket. Achieving this velocity is fundamental in mission planning and launch vehicle design to ensure that spacecraft can successfully enter orbit or travel to other celestial bodies.\u001b[00m\n",
      "\u001b[1m\u001b[93m \n",
      "\n",
      "=====\n",
      "## Please provide feedback on the Final Result and the Agent's actions:\u001b[00m\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " Can I get to low Earth orbit with my 4500000kg rocket that is holding 4450000kg of fuel that has engine exhaust velocity of 19800m/s?\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m\u001b[95m# Agent:\u001b[00m \u001b[1m\u001b[92mAeronautical Engineer\u001b[00m\n",
      "\u001b[95m## Thought:\u001b[00m \u001b[92mThought: To determine if the rocket can reach low Earth orbit (LEO), I need to calculate the delta-v using the ideal rocket equation (Tsiolkovsky Equation). For this, I will use the mass of the rocket, the mass of the fuel, and the exhaust velocity of the rocket's engine.\n",
      "The initial mass of the rocket includes the rocket itself plus the fuel, and the final mass is just the mass of the rocket after the fuel has been expended. \n",
      "- Initial mass: 4,500,000 kg (rocket + fuel)\n",
      "- Final mass: 500,000 kg (rocket after fuel is spent)\n",
      "- Exhaust velocity: 19,800 m/s\n",
      "Now I will perform the delta-v calculation.\u001b[00m\n",
      "\u001b[95m## Using tool:\u001b[00m \u001b[92mAICatalog__AISchema__calculate_delta_v\u001b[00m\n",
      "\u001b[95m## Tool Input:\u001b[00m \u001b[92m\n",
      "\"{\\\"initial_mass\\\": 4500000, \\\"final_mass\\\": 500000, \\\"exhaust_velocity\\\": 19800}\"\u001b[00m\n",
      "\u001b[95m## Tool Output:\u001b[00m \u001b[92m\n",
      "{\"format\": \"SCALAR\", \"value\": \"43505.046631257144\"}\u001b[00m\n",
      "\n",
      "\n",
      "\u001b[1m\u001b[95m# Agent:\u001b[00m \u001b[1m\u001b[92mAeronautical Engineer\u001b[00m\n",
      "\u001b[95m## Final Answer:\u001b[00m \u001b[92m\n",
      "The delta-v calculated for your rocket, which has an initial mass of 4,500,000 kg (including 4,450,000 kg of fuel) and an engine exhaust velocity of 19,800 m/s, is approximately 43,505 m/s. \n",
      "\n",
      "To reach low Earth orbit (LEO), which typically requires a delta-v of around 7,800 m/s, your rocket has more than sufficient delta-v capability. This means that you can indeed achieve low Earth orbit with your current rocket configuration and fuel supply. \n",
      "\n",
      "This result demonstrates a fundamental principle in aeronautical engineering: the efficiency of rocket propulsion systems is paramount in determining the performance of launch vehicles and their capability to reach desired orbits or destinations in space.\u001b[00m\n",
      "\n",
      "\n",
      "\u001b[1m\u001b[95m# Agent:\u001b[00m \u001b[1m\u001b[92mAuditor\u001b[00m\n",
      "\u001b[95m## Task:\u001b[00m \u001b[92mReview and evaluate the tool call output and provide a final answer to the questionCreate a structured log that captures all evaluations made, changes implemented, and final outputs. Ensure this documentation is clear and accessible for future reference.\u001b[00m\n",
      "\n",
      "\n",
      "\u001b[1m\u001b[95m# Agent:\u001b[00m \u001b[1m\u001b[92mAuditor\u001b[00m\n",
      "\u001b[95m## Final Answer:\u001b[00m \u001b[92m\n",
      "### Structured Evaluation Log\n",
      "\n",
      "**1. Context of Evaluation**  \n",
      "- The rocket involved has an initial mass of 4,500,000 kg, inclusive of 4,450,000 kg of fuel.  \n",
      "- The engine exhaust velocity is established at 19,800 m/s.\n",
      "\n",
      "**2. Delta-V Calculation**  \n",
      "- The calculated delta-v for the rocket is approximately 43,505 m/s.  \n",
      "\n",
      "**3. Requirement for Low Earth Orbit (LEO)**  \n",
      "- The typical delta-v required to achieve LEO is around 7,800 m/s.\n",
      "\n",
      "**4. Evaluation**  \n",
      "- Comparison of calculated delta-v to LEO delta-v:  \n",
      "  - **Calculated Delta-V:** 43,505 m/s  \n",
      "  - **Required for LEO:** 7,800 m/s  \n",
      "  - **Conclusion:** The calculated delta-v exceeds the required delta-v for LEO, confirming that the rocket can successfully reach this orbit.\n",
      "\n",
      "**5. Fundamental Principle**  \n",
      "- This evaluation reinforces a key principle in aeronautical engineering: the efficiency of rocket propulsion systems significantly influences the performance of launch vehicles and their ability to attain desired orbits.\n",
      "\n",
      "**6. Changes Implemented**  \n",
      "- No changes were necessary based on the evaluations conducted. The results stand validated.\n",
      "\n",
      "**7. Final Output Summary**  \n",
      "- The rocket's configuration and fuel supply are adequate to reach low Earth orbit, as demonstrated by the delta-v capability significantly surpassing the required threshold for LEO. \n",
      "\n",
      "This structured log summarizes all evaluations made, captures the clear outcome, and is accessible for future reference in aeronautical engineering contexts.\u001b[00m\n",
      "\n",
      "\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "CrewOutput(raw=\"### Structured Evaluation Log\\n\\n**1. Context of Evaluation**  \\n- The rocket involved has an initial mass of 4,500,000 kg, inclusive of 4,450,000 kg of fuel.  \\n- The engine exhaust velocity is established at 19,800 m/s.\\n\\n**2. Delta-V Calculation**  \\n- The calculated delta-v for the rocket is approximately 43,505 m/s.  \\n\\n**3. Requirement for Low Earth Orbit (LEO)**  \\n- The typical delta-v required to achieve LEO is around 7,800 m/s.\\n\\n**4. Evaluation**  \\n- Comparison of calculated delta-v to LEO delta-v:  \\n  - **Calculated Delta-V:** 43,505 m/s  \\n  - **Required for LEO:** 7,800 m/s  \\n  - **Conclusion:** The calculated delta-v exceeds the required delta-v for LEO, confirming that the rocket can successfully reach this orbit.\\n\\n**5. Fundamental Principle**  \\n- This evaluation reinforces a key principle in aeronautical engineering: the efficiency of rocket propulsion systems significantly influences the performance of launch vehicles and their ability to attain desired orbits.\\n\\n**6. Changes Implemented**  \\n- No changes were necessary based on the evaluations conducted. The results stand validated.\\n\\n**7. Final Output Summary**  \\n- The rocket's configuration and fuel supply are adequate to reach low Earth orbit, as demonstrated by the delta-v capability significantly surpassing the required threshold for LEO. \\n\\nThis structured log summarizes all evaluations made, captures the clear outcome, and is accessible for future reference in aeronautical engineering contexts.\", pydantic=None, json_dict=None, tasks_output=[TaskOutput(description='Call tools that are relevant to the posed questionBased on the review of outputs, collate findings and direct responses to the original query while ensuring clarity and accuracy. Highlight any specific aeronautical engineering principles that are relevant to the results.', name=None, expected_output='string', summary='Call tools that are relevant to the posed questionBased on...', raw='The delta-v calculated for your rocket, which has an initial mass of 4,500,000 kg (including 4,450,000 kg of fuel) and an engine exhaust velocity of 19,800 m/s, is approximately 43,505 m/s. \\n\\nTo reach low Earth orbit (LEO), which typically requires a delta-v of around 7,800 m/s, your rocket has more than sufficient delta-v capability. This means that you can indeed achieve low Earth orbit with your current rocket configuration and fuel supply. \\n\\nThis result demonstrates a fundamental principle in aeronautical engineering: the efficiency of rocket propulsion systems is paramount in determining the performance of launch vehicles and their capability to reach desired orbits or destinations in space.', pydantic=None, json_dict=None, agent='Aeronautical Engineer', output_format=<OutputFormat.RAW: 'raw'>), TaskOutput(description='Review and evaluate the tool call output and provide a final answer to the questionCreate a structured log that captures all evaluations made, changes implemented, and final outputs. Ensure this documentation is clear and accessible for future reference.', name=None, expected_output='string', summary='Review and evaluate the tool call output and provide a...', raw=\"### Structured Evaluation Log\\n\\n**1. Context of Evaluation**  \\n- The rocket involved has an initial mass of 4,500,000 kg, inclusive of 4,450,000 kg of fuel.  \\n- The engine exhaust velocity is established at 19,800 m/s.\\n\\n**2. Delta-V Calculation**  \\n- The calculated delta-v for the rocket is approximately 43,505 m/s.  \\n\\n**3. Requirement for Low Earth Orbit (LEO)**  \\n- The typical delta-v required to achieve LEO is around 7,800 m/s.\\n\\n**4. Evaluation**  \\n- Comparison of calculated delta-v to LEO delta-v:  \\n  - **Calculated Delta-V:** 43,505 m/s  \\n  - **Required for LEO:** 7,800 m/s  \\n  - **Conclusion:** The calculated delta-v exceeds the required delta-v for LEO, confirming that the rocket can successfully reach this orbit.\\n\\n**5. Fundamental Principle**  \\n- This evaluation reinforces a key principle in aeronautical engineering: the efficiency of rocket propulsion systems significantly influences the performance of launch vehicles and their ability to attain desired orbits.\\n\\n**6. Changes Implemented**  \\n- No changes were necessary based on the evaluations conducted. The results stand validated.\\n\\n**7. Final Output Summary**  \\n- The rocket's configuration and fuel supply are adequate to reach low Earth orbit, as demonstrated by the delta-v capability significantly surpassing the required threshold for LEO. \\n\\nThis structured log summarizes all evaluations made, captures the clear outcome, and is accessible for future reference in aeronautical engineering contexts.\", pydantic=None, json_dict=None, agent='Auditor', output_format=<OutputFormat.RAW: 'raw'>)], token_usage=UsageMetrics(total_tokens=5085, prompt_tokens=4068, cached_prompt_tokens=1024, completion_tokens=1017, successful_requests=5))"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from crewai import Agent, Crew, Task\n",
    "\n",
    "# Create agents\n",
    "aeronautical_engineer = Agent(\n",
    "    role=\"Aeronautical Engineer\",\n",
    "    goal=\"Answer questions regarding fundamental concepts in Physics as they relate to Aeronautical Engineering\",\n",
    "    backstory=\"Works at NASA. Loves Physics and Math. Thoroughly believes that The Expanse is superior to Star Wars.\",\n",
    "    expected_output=\"Either the result of a mathematical calculation or a result and an explanation of the calculation\",\n",
    "    tools=tools,\n",
    "    verbose=True,\n",
    ")\n",
    "\n",
    "mission_specialist = Agent(\n",
    "    role=\"Auditor\",\n",
    "    goal=\"Ensures that the Aeronautical Engineer provides correct answers using deterministic tools\",\n",
    "    backstory=\"Loves space. Likes boring days at work. Likes seeing flags planted on planetary bodies.\",\n",
    "    expected_output=\"A full explanation of the calculated result with both a lay person's and a highly technical audience in mind\",\n",
    "    verbose=True,\n",
    ")\n",
    "\n",
    "# Define tasks\n",
    "research = Task(\n",
    "    description=\"Call tools that are relevant to the posed question\",\n",
    "    expected_output=\"string\",\n",
    "    agent=aeronautical_engineer,\n",
    "    human_input=True,\n",
    ")\n",
    "\n",
    "review = Task(\n",
    "    description=\"Review and evaluate the tool call output and provide a final answer to the question\",\n",
    "    expected_output=\"string\",\n",
    "    agent=mission_specialist,\n",
    ")\n",
    "\n",
    "# Assemble a crew with planning enabled\n",
    "crew = Crew(\n",
    "    agents=[aeronautical_engineer, mission_specialist],\n",
    "    tasks=[research, review],\n",
    "    verbose=True,\n",
    "    planning=True,  # Enable planning feature\n",
    ")\n",
    "\n",
    "# Execute tasks\n",
    "crew.kickoff()\n",
    "\n",
    "# Human input (try something different and see what happens!):\n",
    "# Can I get to low Earth orbit with my 4500000kg rocket that is holding 4450000kg of fuel that has engine exhaust velocity of 19800m/s?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "921279a8-8c56-4a84-b68c-f1907212b44e",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
